import json
import os

def convert_txt_to_json(txt_file_path):
    words = []
    with open(txt_file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            
            parts = line.split('\t')
            if len(parts) != 2:
                continue
                
            word, definition = parts
            # 从定义中提取词性（如果有）
            pos = ''
            if definition.startswith(('n.', 'v.', 'adj.', 'adv.', 'prep.', 'conj.', 'pron.', 'num.')):
                pos = definition.split('.')[0] + '.'
            
            word_obj = {
                "word": word,
                "definition": definition,
                "type": "word",
                "difficulty": 1,
                "pos": pos  # 添加词性字段
            }
            words.append(word_obj)
    
    # 创建输出的json文件路径
    output_path = txt_file_path.replace('.txt', '.json')
    
    # 写入json文件
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump({"words": words}, f, ensure_ascii=False, indent=2)
    
    print(f"Converted {txt_file_path} to {output_path} with {len(words)} words")

def main():
    # 获取word_banks目录的路径
    word_banks_dir = os.path.join('typing_game', 'data', 'word_banks')
    
    # 遍历目录中的所有.txt文件
    for filename in os.listdir(word_banks_dir):
        if filename.endswith('.txt'):
            txt_file_path = os.path.join(word_banks_dir, filename)
            convert_txt_to_json(txt_file_path)

if __name__ == '__main__':
    main() 